//
//  LoginOrRegisterViewController.m
//  YSSmartHome
//
//  Created by Yahaong on 16/8/10.
//  Copyright © 2016年 yahaong. All rights reserved.
//

#import "LoginOrRegisterViewController.h"
#import "MQTTSessionManager.h"
#import "ZTDeviceUtil.h"
#import "TabBarController.h"
#import "AppDelegate.h"
#import "DataManager.h"
#import "RegisterViewController.h"
#import "ZTNetTest.h"
#import "UIView+HUD.h"
#import "YSCommon.h"
#import "UIView+HUD.h"
#import <XAISDK/XAI.h>

@interface LoginOrRegisterViewController ()
@property(nonatomic, strong)UIImageView *m_imgBackground;
@property(nonatomic, strong)UIImageView *m_imgIcon;
@property(nonatomic, strong)UIImageView *m_imgPhoneNumber;
@property(nonatomic, strong)UITextField *m_textPhoneNumber;
@property(nonatomic, strong)UIImageView *m_imgPassword;
@property(nonatomic, strong)UITextField *m_textPassword;
@property(nonatomic, strong)UIButton    *m_btnLogin;
@property(nonatomic, strong)UIButton    *m_btnFroget;
@property(nonatomic, strong)UIButton    *m_btnRegister;
@property(nonatomic, strong)ZTUser      *m_currentUser;
@property(nonatomic, strong)ZTNetTest   *m_netTest;
@property(nonatomic, strong)UIView      *m_phoneSplitView;
@property(nonatomic, strong)UIView     *m_passwordSplitView;
@end

@implementation LoginOrRegisterViewController

#pragma mark - life cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initSubviews];
    ZTUser *user = [ZTUser unarchiver];
    self.m_textPhoneNumber.text = user.m_strTel;
    self.m_textPassword.text = user.m_strPwd;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

#pragma mark - event response

- (void)loginBtnClick {
    if (![MQTTCoverTool isMobileNumber:self.m_textPhoneNumber.text]) {
        [self.view yh_showMsgHUD:@"输入的手机号不正确"];
        return;
    }
    if (self.m_textPassword.text.length < 6) {
        [self.view yh_showMsgHUD:@"密码长度不对"];
        return;
    }
    if ([kMQTTSessionManager.xai isConnected]) {
        [kMQTTSessionManager.xai close];
    }
    [self.view yh_showLoadingHUD];
    XAI* xai = [[XAI alloc]initWithHost:kZTMQTTBaseURL port:kZTMQTTBasePort];
    kMQTTSessionManager.xai = xai;
    kMQTTSessionManager.xai.delegate = kMQTTSessionManager;
    __weak typeof(self)wself = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        __strong typeof(wself)sself = wself;
        if (!sself){
            return;
        }
        [xai startWithAccount:sself.m_textPhoneNumber.text password:sself.m_textPassword.text success:^{
            ZTUser *user = [ZTUser userWithTelNum:sself.m_textPhoneNumber.text pawd:sself.m_textPassword.text];
            [user archiver];
            kMQTTSessionManager.isLogin = YES;
            kMQTTSessionManager.currentUser = user;
            dispatch_async(dispatch_get_main_queue(), ^{
                [sself.view yh_hideAllHUD];
                [sself.view yh_showMsgHUD:@"登录成功"];
                [[NSNotificationCenter defaultCenter]postNotificationName:kZTSwitchRootViewControllerKey object:@(1)];
            });
        } error:^(NSUInteger code) {
            [kMQTTSessionManager.xai close];
            kMQTTSessionManager.isLogin = NO;
            dispatch_async(dispatch_get_main_queue(), ^{
                [sself.view yh_hideAllHUD];
                [sself.view yh_showMsgHUD:@"登录出错"];
            });
        }];
    });
}

//忘记密码或者注册按钮点击
- (void)btnClick:(UIButton *)btn
{
    RegisterViewController *vc = [[RegisterViewController alloc]init];
    if (btn == self.m_btnRegister) {
        vc.flag = YES;
        vc.navigationItem.title = @"注册帐号";
    }else {
        vc.flag = NO;
        vc.navigationItem.title = @"重置密码";
    }
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
}

#pragma mark - private method
- (void)initSubviews {
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self.view addSubview:self.m_imgBackground];
    [self.view addSubview:self.m_imgIcon];
    [self.view addSubview:self.m_imgPhoneNumber];
    [self.view addSubview:self.m_textPhoneNumber];
    [self.view addSubview:self.m_phoneSplitView];
    [self.view addSubview:self.m_imgPassword];
    [self.view addSubview:self.m_textPassword];
    [self.view addSubview:self.m_passwordSplitView];
    [self.view addSubview:self.m_btnLogin];
    [self.view addSubview:self.m_btnFroget];
    [self.view addSubview:self.m_btnRegister];
    [self layoutPageSubviews];
}

- (void)layoutPageSubviews {
    [self.m_imgBackground mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.m_imgIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(kIphoneSize_Widith(100));
        make.height.equalTo(kIphoneSize_Height(98));
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view).offset(kIphoneSize_Height(133));
    }];
    
    [self.m_imgPhoneNumber mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.m_imgIcon.bottom).offset(kIphoneSize_Height(55));
        make.leading.equalTo(kIphoneSize_Widith(50));
        make.size.equalTo(CGSizeMake(kIphoneSize_Widith(18), kIphoneSize_Height(25)));
    }];

    [self.m_textPhoneNumber mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.m_imgPhoneNumber);
        make.leading.equalTo(self.m_imgPhoneNumber.trailing).offset(kIphoneSize_Widith(16));
        make.trailing.equalTo(self.view).offset(kIphoneSize_Widith(-52));
    }];
    
    
    [self.m_phoneSplitView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.m_textPhoneNumber);
        make.top.equalTo(self.m_textPhoneNumber.bottom);
        make.height.equalTo(1);
    }];
    
    [self.m_imgPassword mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.m_phoneSplitView.bottom).offset(kIphoneSize_Height(42));
        make.leading.equalTo(self.m_imgPhoneNumber);
        make.size.equalTo(self.m_imgPhoneNumber);
    }];
    
    [self.m_textPassword mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.m_imgPassword);
        make.leading.trailing.equalTo(self.m_textPhoneNumber);
    }];
    
    [self.m_passwordSplitView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.m_textPassword);
        make.top.equalTo(self.m_textPassword.bottom);
        make.height.equalTo(1);
    }];
    
    [self.m_btnLogin mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.view).offset(kIphoneSize_Widith(31));
        make.trailing.equalTo(self.view).offset(kIphoneSize_Widith(-31));
        make.top.equalTo(self.m_imgPassword.bottom).offset(kIphoneSize_Height(52));
        make.height.equalTo(kIphoneSize_Height(47));
    }];
    
    [self.m_btnFroget mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.m_btnLogin);
        make.top.equalTo(self.m_btnLogin.bottom).offset(kIphoneSize_Height(25));
    }];
    
    [self.m_btnRegister mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self.m_btnLogin);
        make.top.equalTo(self.m_btnFroget);
    }];
}
    
- (void)getData:(XAITYPEAPSN)apsn {
    [ZTDeviceUtil findAllDevWithApsn:apsn];
}

#pragma mark - getters and setters
- (UIImageView *)m_imgBackground
{
    if (!_m_imgBackground) {
        _m_imgBackground = [[UIImageView alloc]init];
        _m_imgBackground.backgroundColor = [UIColor whiteColor];
    }
    return _m_imgBackground;
}
- (UIImageView *)m_imgIcon
{
    if (!_m_imgIcon) {
        _m_imgIcon = [[UIImageView alloc]init];
        _m_imgIcon.image = [UIImage imageNamed:@"yushu_icon"];
    }
    return _m_imgIcon;
}

- (UIImageView *)m_imgPhoneNumber
{
    if (!_m_imgPhoneNumber) {
        _m_imgPhoneNumber = [[UIImageView alloc]init];
        _m_imgPhoneNumber.image = [UIImage imageNamed:@"phoneicon"];
    }
    return _m_imgPhoneNumber;
}
- (UIImageView *)m_imgPassword
{
    if (!_m_imgPassword) {
        _m_imgPassword = [[UIImageView alloc]init];
        _m_imgPassword.image = [UIImage imageNamed:@"passwordicon"];
    }
    return _m_imgPassword;
}

- (UITextField *)m_textPhoneNumber
{
    if (!_m_textPhoneNumber ) {
        _m_textPhoneNumber = [[UITextField alloc]init];
        _m_textPhoneNumber.placeholder = @"请输入手机号";
        _m_textPhoneNumber.textColor = RGBColor(153, 153, 153);
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSForegroundColorAttributeName] = RGBColor(153, 153, 153);
        NSAttributedString *attribute = [[NSAttributedString alloc] initWithString:@"请输入手机号" attributes:dict];
        [_m_textPhoneNumber setAttributedPlaceholder:attribute];
        _m_textPhoneNumber.keyboardType = UIKeyboardTypeNumberPad;
        _m_textPhoneNumber.clearButtonMode = UITextFieldViewModeWhileEditing;
        _m_textPassword.secureTextEntry = YES;
        
    }
    return _m_textPhoneNumber;
}

-(UITextField*)m_textPassword
{
    if (!_m_textPassword) {
        _m_textPassword = [[UITextField alloc]init];
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSForegroundColorAttributeName] = RGBColor(153, 153, 153);
        NSAttributedString *attribute = [[NSAttributedString alloc] initWithString:@"请输入密码" attributes:dict];
        [_m_textPassword setAttributedPlaceholder:attribute];
        _m_textPassword.textColor = RGBColor(153, 153, 153);
        _m_textPassword.clearButtonMode = UITextFieldViewModeWhileEditing;
        _m_textPassword.secureTextEntry = YES;
        
    }
    return _m_textPassword;
}
- (UIButton *)m_btnLogin
{
    if (!_m_btnLogin) {
        _m_btnLogin = [UIButton buttonWithType:UIButtonTypeCustom];
        [_m_btnLogin setTitle:@"登录" forState:UIControlStateNormal];
        _m_btnLogin.titleLabel.font = [UIFont systemFontOfSize:17];
        _m_btnLogin.backgroundColor = RGBColor(0, 169, 253);
        _m_btnLogin.layer.cornerRadius = 5;
        _m_btnLogin.layer.masksToBounds = YES;
        [_m_btnLogin addTarget:self action:@selector(loginBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _m_btnLogin;
}
- (UIButton *)m_btnFroget
{
    if (!_m_btnFroget) {
        _m_btnFroget = [UIButton buttonWithType:UIButtonTypeCustom];
        [_m_btnFroget setTitle:@"忘记密码" forState:UIControlStateNormal];
        _m_btnFroget.backgroundColor = [UIColor clearColor];
        [_m_btnFroget setTitleColor:RGBColor(102, 102, 102) forState:UIControlStateNormal];
        [_m_btnFroget addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _m_btnFroget;
}
- (UIButton *)m_btnRegister
{
    if (!_m_btnRegister) {
        _m_btnRegister = [UIButton buttonWithType:UIButtonTypeCustom];
        [_m_btnRegister setTitle:@"注册帐号" forState:UIControlStateNormal];
        _m_btnRegister.backgroundColor = [UIColor clearColor];
        [_m_btnRegister setTitleColor:RGBColor(102, 102, 102) forState:UIControlStateNormal];
        [_m_btnRegister addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _m_btnRegister;
}

- (UIView *)m_phoneSplitView
{
    if (!_m_phoneSplitView) {
        _m_phoneSplitView = [[UIView alloc]init];
        _m_phoneSplitView.backgroundColor = RGBColor(204, 204, 204);
    }
    return _m_phoneSplitView;
}
- (UIView *)m_passwordSplitView
{
    if (!_m_passwordSplitView) {
        _m_passwordSplitView = [[UIView alloc]init];
        _m_passwordSplitView.backgroundColor = RGBColor(204, 204, 204);
    }
    return _m_passwordSplitView;
}
@end
